package com.hsnn.medstgmini.controller;

import java.util.Calendar;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.hsnn.medstgmini.Constants;
import com.hsnn.medstgmini.sys.model.SysRole;
import com.hsnn.medstgmini.sys.model.SysUser;
import com.hsnn.medstgmini.sys.service.SysRoleManager;
import com.hsnn.medstgmini.sys.service.SysUserManager;
import com.hsnn.medstgmini.util.Pagination;

@Controller
public class ExpertPasswordChangeController{
	
	private static final Logger log = Logger.getLogger(ExpertPasswordChangeController.class);
	
	@Autowired
	private HttpServletRequest request;

	@Autowired
	private SysUserManager userManager;
	
	@Autowired
	private SysRoleManager sysRoleManager;
	
	@RequestMapping("toExpertChangePassword")
	public String toExpertPasswordChange(){
		return "/ExpertChangePassword";
	}
	
	@RequestMapping("/expertPasswordChange")
	@ResponseBody
	public Pagination expertPasswordChange(Model model){
		Pagination page = new Pagination();
		String oldPassword = DigestUtils.md5Hex(request.getParameter("oldPassword"));//旧密码
		String newPassword = DigestUtils.md5Hex(request.getParameter("newPassword"));//新密码
		try{
			SysUser user=(SysUser) request.getSession().getAttribute(Constants.USERINFO);
			String password = user.getPassword();
			if(!oldPassword.equals(password)){
				page.setSuccess(false);
				page.setMsg("旧密码输入错误！请重新输入！");
			}
			user.setPassword(newPassword);
			user.setUpdDateTime(new Date());
			user.setUpdUser(user.getName());
			Calendar c = Calendar.getInstance();
			c.add(Calendar.MONTH, +5);
			SysRole role = new SysRole();
			role.setId(Constants.EXPERT_SYS_ROLE_ID);
			user.setPasswordExpired(c.getTime());
			user.setRole(role);
			userManager.zxSaveUser(Constants.OP_TYPE_EDIT, user, null);	
			page.setMsg("密码修改成功");
			page.setSuccess(true);
			
		}catch(Exception e){
			log.error("",e);
            page.setSuccess(false);
            page.setMsg("密码修改失败");
		}
		return page;
	}
	@RequestMapping("toExpertLogout")
	public String toExpertLogout(){
		HttpSession session = request.getSession();
		if (session != null) {
			session.setAttribute(Constants.USERINFO, null);
			session.invalidate();
		}
		return "/login";
	}
}
